// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { cartList:[] }
  },

  getters:{
    count(){
      return this.cartList.length
    }
  },
  // 也可以这样定义
  // state: () => ({ count: 0 })
 actions:{
  addCart (id) {
    // 先判断购物车是否已有，如果有，数量+1
    const isAdded = this.cartList.find(item => item.id === id);
    if (isAdded) {
        isAdded.count ++;
    } else {
        this.cartList.push({
            id: id,
            count: 1
        })
    }
  },
    // 修改商品数量
    editCartCount (payload) {
      const product = this.cartList.find(item => item.id === payload.id);
      product.count += payload.count;
  },
  // 删除商品
  deleteCart (id) {
      const index = this.cartList.findIndex(item => item.id === id);
      this.cartList.splice(index, 1);
  },
  // 清空购物车
  emptyCart () {
      this.cartList = [];
  }
 }
})